import Map from 'ol/Map'
import './style.css'
import 'ol/ol.css'
import View from 'ol/View'
import { Vector, XYZ } from 'ol/source'
import TileLayer from 'ol/layer/Tile'
import Feature from 'ol/Feature'
import { Point } from 'ol/geom'
import VectorLayer from 'ol/layer/Vector'
import Style from 'ol/style/Style'
import Icon from 'ol/style/Icon'

const target = 'map'

const view = new View({
    // 南京经纬度
    center: [118.796877, 32.060255],
    zoom: 10,
    projection: 'EPSG:4326'
})

const layers = [new TileLayer({
    source: new XYZ({
        url: 'http://wprd0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}'
    })
})]

const map = new Map({
    target,
    view,
    layers
})

// 通过 ol 中提高的要素

// 创建要素（二维中要素主要是：点 线 面）并且将要素绘制到底图上 feature => 1. 几何形状 2.属性信息

// 通过 canvas 绘制一个点
const canvas = document.createElement('canvas')
canvas.width = 30
canvas.height = 30
const context = canvas.getContext('2d')
context.fillStyle = 'green'
context.beginPath()
context.arc(15, 15, 15, 0, 2 * Math.PI)
context.fill()

// 1. 创建点要素，并且在这个点要素上绘制一个简单的 icon 
const iconFeature = new Feature({
    geometry: new Point([118.796877, 32.060255]),
})

// 1.1 设置要素的样式
iconFeature.setStyle(new Style({
    // 加载一个 icon 图片
    // image: new Icon({
    //     src: './public/icon.png',
    //     scale: 0.1 // 缩放
    // })
    // 加载 canvas 图
    image: new Icon({
        img: canvas,
        imgSize: [15, 15], // 图片大小
        scale: 0.5
    })
}))

// 2. 创建一个矢量源，将这个点要素添加到矢量源中
const iconSource = new Vector({
    features: [iconFeature]
})

// 3. 创建一个矢量图层，将矢量源添加到矢量图层中
const iconLayer = new VectorLayer({
    source: iconSource
})

// 4. 将矢量图层添加到地图中
map.addLayer(iconLayer)